<?php

namespace App\Jobs\Export;

use App\Models\Activity\ActivityActionModel;
use App\Models\Activity\ActivityModel;
use App\Models\Activity\ActivityShopJoinModel;
use App\Models\Activity\ShopOrderActivityModel;
use App\Models\Article\ArticleCategoryModel;
use App\Models\Article\ArticleModel;
use App\Remote\Rms\RmsExportRemote;
use App\Service\Activity\ActivityDataService;
use App\Service\Activity\ShopOrderActivityService;
use App\Service\Article\ArticleCategoryService;
use App\Service\Article\ArticleOperateService;
use App\Service\Common\ExportService;
use App\Service\Cruise\Check\CruiseCheckReportService;
use App\Service\Cruise\Shop\CruiseShopLicenseRecordsService;
use App\Service\Invoice\Web\InvoiceService;
use App\Service\Kms\Album\AlbumResourceService;
use App\Service\WorkOrder\Appraise\AppraiseService;
use App\Service\WorkOrder\Web\OrderListService;
use Box\Spout\Common\Exception\InvalidArgumentException;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Type;
use Box\Spout\Writer\Exception\WriterNotOpenedException;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Kuafu\File\FileUtil;
use Maatwebsite\Excel\Exceptions\NoTypeDetectedException;
use OSS\Core\OssException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class Export implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    const QUEUE_NAME = '{tiger-export}';

    const TYPE_WORK_ORDER                    = 'WorkOrder';     //工单导出 workOrder/web/orderLists?export=true 对应rms ExportDownloadModel 导出类型
    const TYPE_APPRAISE                      = 'Appraise';      //评价反馈导出 appraise/lists?export=1 对应rms ExportDownloadModel 导出类型
    const TYPE_ALBUM_RESOURCE                = 'AlbumResource'; //运营app - 相册资源 批量下载
    const TYPE_INVOICE                       = 'Invoice';       //运营管理-财务分析-查看开票记录列表
    const TYPE_ARTICLE_HOLISTIC_ANALYSIS     = 'ARTICLE_HOLISTIC_ANALYSIS';       //内容管理 - 文章整体分析
    const TYPE_ARTICLE_SINGLE_ANALYSIS       = 'ARTICLE_SINGLE_ANALYSIS';       //内容管理 - 单篇文章分析
    const TYPE_CATEGORY_HOLISTIC_ANALYSIS    = "CATEGORY_HOLISTIC_ANALYSIS"; // web-tiger-专题管理 - 整体分析
    const TYPE_CATEGORY_SINGLE_ANALYSIS      = "CATEGORY_SINGLE_ANALYSIS"; // web-tiger-专题管理 - 单个分析
    const TYPE_SHOP_ORDER_ACTIVITY_SHOP_LIST = "SHOP_ORDER_ACTIVITY_SHOP_LIST"; // web-tiger-门店订货活动
    const TYPE_SHOP_ACTIVITY_SHOP_LIST       = "SHOP_ACTIVITY_SHOP_LIST"; // web-tiger-门店活动门店数据
    const TYPE_SHOP_ACTIVITY_LIST            = "SHOP_ACTIVITY_LIST"; // web-tiger-门店活动
    const TYPE_SHOP_LICENSE_RECORDS_LIST     = "SHOP_LICENSE_RECORDS_LIST"; // web-tiger-门店证件备案列表
    const TYPE_CRUISE_CHECK_REPORT           = "CRUISE_CHECK_REPORT"; // web-tiger-巡检报告

    const TYPE_TO_RMS_CODE_MAP = [
        self::TYPE_WORK_ORDER                    => 400,
        self::TYPE_APPRAISE                      => 401,
        self::TYPE_ALBUM_RESOURCE                => 402,
        self::TYPE_ARTICLE_HOLISTIC_ANALYSIS     => 403,
        self::TYPE_ARTICLE_SINGLE_ANALYSIS       => 404,
        self::TYPE_CATEGORY_HOLISTIC_ANALYSIS    => 405,
        self::TYPE_CATEGORY_SINGLE_ANALYSIS      => 406,
        self::TYPE_SHOP_ORDER_ACTIVITY_SHOP_LIST => 407,
        self::TYPE_SHOP_ACTIVITY_SHOP_LIST       => 408,
        self::TYPE_SHOP_ACTIVITY_LIST            => 409,
        self::TYPE_SHOP_LICENSE_RECORDS_LIST     => 410,

        // TIGER专用的code，后面都用1000+
        self::TYPE_CRUISE_CHECK_REPORT           => 1000,
    ];

    public $timeout = 1800;

    private string $fileNamePrefix;
    private string $type;
    private array  $data;

    /**
     * 导出文件队列
     *
     * @param string $fileNamePrefix
     * @param string $type
     * @param array $data
     */
    public function __construct(string $fileNamePrefix, string $type, array $data)
    {
        $this->fileNamePrefix = $fileNamePrefix;//文件名前缀
        $this->type           = $type;          //类型
        $this->data           = $data;          //导出参数
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info("导出start:", ['fileNamePrefix' => $this->fileNamePrefix, 'type' => $this->type, 'data' => $this->data]);
        if (!in_array($this->type, array_keys(self::TYPE_TO_RMS_CODE_MAP))) {
            Log::info("导出类型不匹配:", ['fileNamePrefix' => $this->fileNamePrefix, 'type' => $this->type, 'data' => $this->data]);
            return;
        }
        $path = '';

        //先请求rms 创建导出中的记录
        $export = RmsExportRemote::exportAdd(
            self::TYPE_TO_RMS_CODE_MAP[$this->type], $this->fileNamePrefix, [
            'showStartAt' => $this->data['startTime'] ?? '',
            'showEndAt'   => $this->data['endTime'] ?? '',
        ], $this->data['userId'] ?? 0
        ) ?? [];
        if (!$export) {
            Log::info("导出远程调用rms失败:", ['fileNamePrefix' => $this->fileNamePrefix, 'type' => $this->type, 'data' => $this->data]);
            return;
        }

        //原导出处理逻辑
        switch ($this->type) {
            case self::TYPE_WORK_ORDER:
                $res = (new OrderListService())->orderLists($this->data['data'], $this->data['userId'], $this->data['export']);
                if ($res) {
                    $path = $res['url'] ? str_replace(FileUtil::domain() . '/', '', $res['url']) : "";
                }
                Log::info("导出调用orderLists:", ['res' => $res, 'path' => $path]);
                break;
            case self::TYPE_APPRAISE:
                $exportType = $this->data['exportType'] ?? self::TYPE_APPRAISE;
                if ($exportType == self::TYPE_INVOICE) {
                    $res = InvoiceService::lists($this->data['data']['data'], $this->data['data']['pageSize'], $this->data['data']['pageNum'], $this->data['data']['export']);
                } else {
                    $res = AppraiseService::lists(
                        $this->data['data']['startTime'], $this->data['data']['endTime'], $this->data['data']['dealStartTime'],
                        $this->data['data']['dealEndTime'], $this->data['data']['status'], $this->data['data']['score'],
                        $this->data['data']['type'], $this->data['data']['tag'], $this->data['data']['shopInfo'],
                        $this->data['data']['dealUid'], $this->data['data']['export'], $this->data['data']['pageSize'],
                        $this->data['data']['pageNum'], $this->data['data']['currentUid']
                    );
                }
                if ($res) {
                    $path = $res['url'] ? str_replace(FileUtil::domain() . '/', '', $res['url']) : "";
                }
                Log::info("导出调用AppraiseServiceLists:", ['res' => $res, 'path' => $path]);
                break;
            case self::TYPE_ALBUM_RESOURCE:
                $res = AlbumResourceService::batchDownloadAlbumResource($this->data['data']['ids'], $this->data['data']['uid']);
                if ($res) {
                    $path = $res['url'] ? str_replace(FileUtil::domain() . '/', '', $res['url']) : "";
                }
                Log::info("批量下载图片batchDownloadAlbumResource:", ['res' => $res, 'path' => $path]);
                break;
            case self::TYPE_CRUISE_CHECK_REPORT:
                $path = CruiseCheckReportService::exportLists($this->data);
                break;
            default:
                $functionName = "exportType_".self::TYPE_TO_RMS_CODE_MAP[$this->type];
                if(method_exists($this, $functionName)){
                    $path = $this->{$functionName}();
                }
                break;
        }

        //导出完成 更新rms 导出表记录
        RmsExportRemote::exportFinish($export['id'], $path);
        Log::info("导出end:", ['fileNamePrefix' => $this->fileNamePrefix, 'type' => $this->type, 'data' => $this->data, 'path' => $path]);
    }

    /**
     * 文章整体分析导出
     *
     * @return array|string|string[]
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws WriterNotOpenedException
     * @throws BindingResolutionException
     * @throws OssException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function exportType_403()
    {
        $contents = ArticleOperateService::getArticleList(
            $this->data['data']["id"],
            $this->data['data']["statisticalStartAt"],
            $this->data['data']["statisticalEndAt"]
        );

        $ossDetail = ExportService::export(
            $this->fileNamePrefix,
            [
                "日期",
                "内容数",
                "展示数",
                "阅读数",
                "点赞数",
                "分享数",
                "收藏数"
            ],
            collect($contents["totalList"])->map(function ($row, $date) {
                return [
                    $date,
                    $row["totalArticle"],
                    $row["showNum"],
                    $row["readNum"],
                    $row["supportNum"],
                    $row["forwardNum"],
                    $row["collectNum"]
                ];
            })->values()->toArray()
        );

        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }

    /**
     * 文章单篇分析导出
     *
     * @return array|string|string[]
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws WriterNotOpenedException
     * @throws BindingResolutionException
     * @throws OssException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function exportType_404()
    {
        $contents = ArticleOperateService::getArticleList(
            $this->data['data']["id"],
            $this->data['data']["statisticalStartAt"],
            $this->data['data']["statisticalEndAt"]
        );

       $article =  ArticleModel::query()->where("id", $this->data['data']["id"])->first();
        $ossDetail = ExportService::export(
            $this->fileNamePrefix,
            [
                "日期",
                "标题",
                "类型",
                "展示数",
                "阅读数",
                "点赞数",
                "分享数",
                "收藏数"
            ],
            collect($contents["totalList"])->map(function ($row, $date) use($article){
                return [
                    $date,
                    $article->title,
                    ArticleModel::TYPE_TEXT[$article->type] ?? "",
                    $row["showNum"],
                    $row["readNum"],
                    $row["supportNum"],
                    $row["forwardNum"],
                    $row["collectNum"]
                ];
            })->values()->toArray()
        );

        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }

    /**
     * 专题整体分析导出
     *
     * @return array|string|string[]
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws WriterNotOpenedException
     * @throws BindingResolutionException
     * @throws OssException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws Exception
     */
    public function exportType_405()
    {
        $contents  = ArticleCategoryService::groupStatistics((object)$this->data["data"]);
        $ossDetail = ExportService::export(
            $this->fileNamePrefix,
            [
                "日期",
                "总专题数",
                "专题展示数",
                "专题阅读数",
                "专题点赞数",
                "专题分享数",
                "专题收藏数"
            ],
            collect($contents["list"])->map(function ($row) {
                return [
                    $row["date"],
                    $row["categoryNum"],
                    $row["showNum"],
                    $row["readNum"],
                    $row["supportNum"],
                    $row["forwardNum"],
                    $row["collectNum"],
                ];
            })->values()->toArray()
        );

        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }

    /**
     * 专题单独分析导出
     *
     * @return array|string|string[]
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws WriterNotOpenedException
     * @throws BindingResolutionException
     * @throws OssException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws Exception
     */
    public function exportType_406()
    {
        $params               = (object)$this->data["data"];
        $contents             = ArticleCategoryService::groupStatistics($params);
        $articleCategoryModel = ArticleCategoryModel::query()->where("id", $params->categoryId)->first();
        $ossDetail            = ExportService::export(
            $this->fileNamePrefix,
            [
                "日期",
                "专题名称",
                "专题展示数",
                "专题阅读数",
                "专题点赞数",
                "专题分享数",
                "专题收藏数"
            ],
            collect($contents["list"])->map(function ($row) use ($articleCategoryModel) {
                return [
                    $row["date"],
                    $articleCategoryModel->name,
                    $row["showNum"],
                    $row["readNum"],
                    $row["supportNum"],
                    $row["forwardNum"],
                    $row["collectNum"],
                ];
            })->values()->toArray()
        );

        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }

    /**
     * 门店订货活动导出
     *
     * @return array|string|string[]
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws WriterNotOpenedException
     * @throws BindingResolutionException
     * @throws OssException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws Exception
     */
    public function exportType_407()
    {
        $params   = (object)$this->data["data"];
        $contents = ShopOrderActivityService::dataStatisticsShopList($params);
        switch ($params->businessType) {
            case ShopOrderActivityModel::BUSINESS_TYPE_1:
                $header   = [
                    "门店ID",
                    "门店code",
                    "门店名称",
                    "报名时间",
                ];
                $contents = collect($contents)->map(function ($row) {
                    return [
                        $row["shopId"],
                        $row["shopCode"],
                        $row["name"],
                        $row["createdAtText"] ?? "",
                    ];
                })->values()->toArray();
                break;
            case ShopOrderActivityModel::BUSINESS_TYPE_2:
                $header   = [
                    "门店ID",
                    "门店code",
                    "门店名称"
                ];
                $contents = collect($contents)->map(function ($row) {
                    return [
                        $row["shopId"],
                        $row["shopCode"],
                        $row["name"],
                    ];
                })->values()->toArray();
                break;
            case ShopOrderActivityModel::BUSINESS_TYPE_3:
                $header   = [
                    "门店ID",
                    "门店code",
                    "门店名称",
                    "回传时间",
                    "门店联系方式",
                    "活动反馈内容",
                    "活动反馈图片",
                    "活动反馈视频",
                    "提交人"
                ];
                $contents = collect($contents)->map(function ($row) {
                    return [
                        $row["shopId"],
                        $row["shopCode"],
                        $row["name"],
                        $row["createdAtText"],
                        $row["shopContact"],
                        $row["feedback"],
                        implode(PHP_EOL, $row["feedbackImages"]),
                        implode(PHP_EOL, $row["feedbackVideos"]),
                        $row["createdUsername"]
                    ];
                })->values()->toArray();
                break;
            case ShopOrderActivityModel::BUSINESS_TYPE_4:
                $header   = [
                    "门店ID",
                    "门店code",
                    "门店名称",
                ];
                $contents = collect($contents)->map(function ($row) {
                    return [
                        $row["shopId"],
                        $row["shopCode"],
                        $row["name"],
                    ];
                })->values()->toArray();
                break;
        }

        $ossDetail = ExportService::export($this->fileNamePrefix, $header, $contents);
        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }

    /**
     * 品控活动门店数据导出
     *
     * @return array|string|string[]
     * @throws ContainerExceptionInterface
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws NotFoundExceptionInterface
     * @throws OssException
     * @throws WriterNotOpenedException
     */
    public function exportType_408()
    {
        $params   = (object)$this->data["data"];
        $contents = ActivityDataService::joinStatisticsShopList($params);
        switch ($params->businessExportType) {
            case ActivityModel::BUSINESS_EXPORT_TYPE_1:
            case ActivityModel::BUSINESS_EXPORT_TYPE_2:
                $header   = [
                    "门店ID",
                    "门店code",
                    "门店名称",
                    "项目名称",
                    "项目类型",
                    "项目动作",
                    "配送地址",
                    "省份",
                    "城市",
                    "区域",
                    "负责督导",
                    "提交人",
                    "报名/支付时间",
                ];

                $contents = collect($contents)->map(function ($row) {
                    $shopAddress = explode("-", attributeGet($row, "shopDetailRel.addressPrefix", ""));
                    list($province, $city, $district) = [
                        $shopAddress[0] ?? "",
                        $shopAddress[1] ?? "",
                        $shopAddress[2] ?? "",
                    ];
                    return [
                        attributeGet($row, "shopDetailRel.id", ""),
                        "\t".str_pad(attributeGet($row, "shopDetailRel.shopCode", ""), 4, 0, STR_PAD_LEFT),
                        attributeGet($row, "shopDetailRel.name", ""),
                        attributeGet($row, "activityRel.name", ""),
                        ActivityModel::ACTIVITY_TYPE_TEXT[attributeGet($row, "activityRel.activityType", "")] ?? "",
                        attributeGet($row, "activityActionRel.name", ""),
                        attributeGet($row, "address", ""),
                        $province,
                        $city,
                        $district,
                        attributeGet($row, "shopDetailRel.councilorRel.name", ""),
                        attributeGet($row, "submitUsername", ""),
                        formatDate(attributeGet($row, "joinTime", 0), ""),
                    ];
                })->values()->toArray();
                break;
            case ActivityModel::BUSINESS_EXPORT_TYPE_3:
            case ActivityModel::BUSINESS_EXPORT_TYPE_4:
                $header   = [
                    "门店ID",
                    "门店code",
                    "门店名称",
                    "项目名称",
                    "项目类型",
                    "项目动作",
                    "回传时间",
                    "提交人联系方式",
                    "提交人",
                    "反馈内容",
                    "反馈图片",
                    "反馈视频",
                    "配送地址",
                    "省份",
                    "城市",
                    "区域",
                    "负责督导",
//                    "提交人",
//                    "报名/支付时间",
                ];

                $contents = collect($contents)->map(function ($row) {
                    $shopAddress = explode("-", attributeGet($row, "shopDetailRel.addressPrefix", ""));
                    list($province, $city, $district) = [
                        $shopAddress[0] ?? "",
                        $shopAddress[1] ?? "",
                        $shopAddress[2] ?? "",
                    ];

                    return [
                        attributeGet($row, "shopDetailRel.id", ""),
                        "\t".str_pad(attributeGet($row, "shopDetailRel.shopCode", ""), 4, 0, STR_PAD_LEFT),
                        attributeGet($row, "shopDetailRel.name", ""),
                        attributeGet($row, "activityRel.name", ""),
                        ActivityModel::ACTIVITY_TYPE_TEXT[attributeGet($row, "activityRel.activityType", "")] ?? "",
                        attributeGet($row, "activityActionRel.name", ""),
                        formatDate(attributeGet($row, "feedbackTime", 0)),
                        attributeGet(
                            $row->joinFeedbackRel->where("key", "shopContact")->first(),
                            "value",
                            ""
                        ),
                        attributeGet($row, "feedbackUsername", ""),
                        attributeGet(
                            $row->joinFeedbackRel->where("key", "feedback")->first(),
                            "value",
                            ""
                        ),
                        implode(PHP_EOL, jsonToArr(attributeGet(
                            $row->joinFeedbackRel->where("key", "feedbackImages")->first(),
                            "value",
                            ""
                        ), [])),
                        implode(PHP_EOL, jsonToArr(attributeGet(
                            $row->joinFeedbackRel->where("key", "feedbackVideos")->first(),
                            "value",
                            ""
                        ), [])),
                        attributeGet($row, "address", ""),
                        $province,
                        $city,
                        $district,
                        attributeGet($row, "shopDetailRel.councilorRel.name", ""),
//                        attributeGet($row, "submitUsername", ""),
//                        formatDate(attributeGet($row, "joinTime", 0), ""),
                    ];
                })->values()->toArray();
                break;
            case ActivityModel::BUSINESS_EXPORT_TYPE_6:
                $header   = [
                    "门店ID",
                    "门店code",
                    "门店名称",
                    "项目名称",
                    "项目类型",
                    "项目动作",
                    "省份",
                    "城市",
                    "区域",
                    "负责督导",
                    "提交人",
                    "报名/支付时间",
                    "是否生成参与记录",
                    "参与渠道",
                    "参与状态",
                    "回传状态",
                ];

                $contents = collect($contents)->map(function ($row) {
                    $joinChannelText = $joinStatusText = $feedbackStatusText = "";

                    // 取优先级最高的status记录
                    $joinRel = ActivityShopJoinModel::query()
                                                    ->with('activityActionRel')
                                                    ->where('activityId', $row->activityId)
                                                    ->where('shopId', $row->shopId)
                                                    ->orderByRaw("FIELD(status, " . implode(',', ActivityShopJoinModel::STATUS_PRIORITY) . ")")
                                                    ->first();


                    if ($joinRel) {
                        $joinText           = "已生成";
                        $joinChannelText    = ActivityActionModel::ACTION_TYPE_TEXT[$joinRel->actionType] ?? "";
                        $joinStatusText     = ActivityShopJoinModel::STATUS_TEXT[$joinRel->status] ?? "";
                        $feedbackStatusText = ActivityShopJoinModel::FEEDBACK_STATUS_TEXT[$joinRel->feedbackStatus] ?? "";
                    } else {
                        $joinText = "未生成";
                    }

                    $shopAddress = explode("-", attributeGet($row, "shopDetailRel.addressPrefix", ""));
                    list($province, $city, $district) = [
                        $shopAddress[0] ?? "",
                        $shopAddress[1] ?? "",
                        $shopAddress[2] ?? "",
                    ];

                    return [
                        attributeGet($row, "shopDetailRel.id", ""),
                        "\t".str_pad(attributeGet($row, "shopDetailRel.shopCode", ""), 4, 0, STR_PAD_LEFT),
                        attributeGet($row, "shopDetailRel.name", ""),
                        attributeGet($row, "activityRel.name", ""),
                        ActivityModel::ACTIVITY_TYPE_TEXT[attributeGet($row, "activityRel.activityType", "")] ?? "",
                        (string)optional(optional($joinRel)->activityActionRel)->name,
                        $province,
                        $city,
                        $district,
                        attributeGet($row, "shopDetailRel.councilorRel.name", ""),
                        $joinRel->submitUsername ?? '',
                        formatDate($joinRel->joinTime ?? 0, ""),
                        $joinText,
                        $joinChannelText,
                        $joinStatusText,
                        $feedbackStatusText
                    ];
                })->values()->toArray();
                break;
        }

        $ossDetail = ExportService::export($this->fileNamePrefix, $header, $contents);
        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }

    /**
     * 品控活动导出
     *
     * @return array|string|string[]
     * @throws ContainerExceptionInterface
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws NotFoundExceptionInterface
     * @throws OssException
     * @throws WriterNotOpenedException
     */
    public function exportType_409()
    {
        $params   = (object)$this->data["data"];
        $contents = ActivityDataService::joinStatistics($params);
        $header   = [
            "id",
            "项目名称",
            "项目类型",
            "有效期类型",
            "开始时间",
            "结束时间",
            "可参加门店数",
            "已参加门店数",
            "待审核门店数",
            "已回传数",
            "最近更新时间",
        ];

        $contents = $contents->map(function (ActivityModel $activityModel) {
            [
                "id"               => $activityModel->id,
                "name"             => $activityModel->name,
                "activityTypeText" => ActivityModel::ACTIVITY_TYPE_TEXT[$activityModel->activityType] ?? "",
//                "actions"          => $activityModel->actionRel,
//                "expireType"       => $activityModel->expireType,
                "expireTypeText"   => ActivityModel::EXPIRE_TYPE_TEXT[$activityModel->expireType] ?? "",
                "startTime"        => formatDate($activityModel->startTime, ""),
                "endTime"          => formatDate($activityModel->endTime, ""),
//                "status"           => $activityModel->status,
                "statusText"       => ActivityModel::STATUS_TEXT[$activityModel->status] ?? "",
                "canJoinCount"     => $activityModel->canJoinCount,
                "hasJoinCount"     => $activityModel->hasJoinCount,
                "reviewCount"      => $activityModel->reviewCount,
                "feedbackCount"    => $activityModel->feedbackCount,
                "updatedAtText"    => $activityModel->updatedAt->format("Y-m-d H:i:s"),
            ];
        })->values()->toArray();

        $ossDetail = ExportService::export($this->fileNamePrefix, $header, $contents);
        $path      = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }

    /**
     * 门店证件备案列表导出
     *
     * @return array|string|string[]
     * @throws IOException
     * @throws InvalidArgumentException
     * @throws WriterNotOpenedException
     * @throws BindingResolutionException
     * @throws OssException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws Exception
     */
    public function exportType_410()
    {
        $params   = $this->data["data"];
        $pageSize               = $params['pageSize'] ?? '';
        $pageNum                = $params['pageNum'] ?? '';
        $shopIds                = $params['shopIds'] ?? '';
        $dimCode                = $params['dimCode'] ?? '';
        $shopStatus             = $params['shopStatus'] ?? '';
        $status                 = $params['status'] ?? '';
        $councilorId            = $params['councilorId'] ?? '';
        $merchantUpdatedAtStart = $params['merchantUpdatedAtStart'] ?? '';
        $merchantUpdatedAtEnd   = $params['merchantUpdatedAtEnd'] ?? '';
        $cruiseAtStart          = $params['cruiseAtStart'] ?? '';
        $cruiseAtEnd            = $params['cruiseAtEnd'] ?? '';
        $activityDays           = $params['activityDays'] ?? '';
        $sortField              = $params['sortField'] ?? '';
        $sortOrder              = $params['sortOrder'] ?? '';

        $list = CruiseShopLicenseRecordsService::list(
            $pageSize, $pageNum, $shopIds, $dimCode, $shopStatus, $status, $councilorId, $merchantUpdatedAtStart,
            $merchantUpdatedAtEnd,
            $cruiseAtStart, $cruiseAtEnd, $activityDays,'', true
        );

        $header = [
            "门店编号",
            "门店名称",
            "门店状态",
            "所属区域",
            "战区",
            "省",
            "市",
            "区",
            "门店督导",
            "备案状态",
            "营业执照",
            "食品经营许可证",
            "主体业态",
            "经营项目",
            "商家最近操作",
            "最近审核时间",
        ];

        $contents = collect($list['list'] ?? [])->map(function ($item) {
            return [
                $item['shopCode'],
                $item['name'],
                $item['shopStatus'],
                $item['addressPrefix'],
                $item['warZone'],
                $item['provinceName'],
                $item['cityName'],
                $item['districtName'],
                $item['councilorName'],
                $item['status'],
                $item['businessLicenseStatus'],
                $item['foodLicenseStatus'],
                $item['mainBusiness'],
                $item['businessScope'],
                $item['merchantUpdatedAt'],
                $item['cruiseAt'],
            ];
        })->values()->toArray();

        $ossDetail = ExportService::export($this->fileNamePrefix, $header, $contents,Type::XLSX);
        unset($contents);
        $path = "";
        if ($ossDetail) {
            $path = $ossDetail['url'] ? str_replace(FileUtil::domain() . '/', '', $ossDetail['url']) : "";
        }
        return $path;
    }
}
